package controller

import (
	"errors"
	"fmt"
	"github.com/cy77cc/hioshop/models"
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type AddressHandler struct{}

func (AddressHandler) GetAddress(c *gin.Context) {
	id, exists := c.Get("id")
	res := utils.NewResponse()
	if !exists {
		res.SetRes(1, "发生错误", nil)
		//global.LOG.Error("获取id发生错误")
		c.JSON(http.StatusBadRequest, res)
		return
	}
	userId := id.(uint)
	address := models.Address{
		UserId: userId,
	}
	list, err := address.GetAddressList()
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		//global.LOG.Error("查询时发生错误：", zap.Error(err))
		res.SetRes(1, "发生错误", err)
		c.JSON(http.StatusBadRequest, res)
		return
	}

	res.SetRes(0, "success", list)
	c.JSON(http.StatusOK, res)
}

func (AddressHandler) SaveAddress(c *gin.Context) {
	id, exists := c.Get("id")
	res := utils.NewResponse()
	if !exists {
		res.SetRes(1, "发生错误", nil)
		//global.LOG.Error("获取id发生错误")
		c.JSON(http.StatusBadRequest, res)
		return
	}
	userId := id.(uint)
	address := models.Address{
		UserId: userId,
	}

	if err := c.ShouldBindJSON(&address); err != nil {
		res.SetRes(1, "解析参数发生错误", nil)
		//global.LOG.Error("解析参数发生错误")
		c.JSON(http.StatusBadRequest, res)
		return
	}

	err := address.Create()
	if err != nil || address.ID <= 0 {
		//global.LOG.Error("创建时发生错误：", zap.Error(err))
		res.SetRes(1, "发生错误", err)
		c.JSON(http.StatusBadRequest, res)
		return
	}

	res.SetRes(0, "success", address)
	c.JSON(http.StatusOK, res)
}

func (AddressHandler) GetAddressDetail(ctx *gin.Context) {
	id, exists := ctx.Get("id")
	addressId := ctx.Query("id")
	res := utils.NewResponse()
	if !exists {
		res.SetRes(1, "发生错误", nil)
		//global.LOG.Error("获取id发生错误")
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	userId := id.(uint)
	address := models.Address{
		UserId: userId,
	}
	aid, _ := strconv.Atoi(addressId)
	address.ID = uint(aid)
	err := address.Query()

	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		//global.LOG.Error("查询时发生错误：", zap.Error(err))
		res.SetRes(1, "发生错误", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	res.SetRes(0, "success", address)
	ctx.JSON(http.StatusOK, res)

}

func (AddressHandler) DeleteAddress(ctx *gin.Context) {
	id, exists := ctx.Get("id")
	res := utils.NewResponse()
	if !exists {
		res.SetRes(1, "发生错误", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	req := struct {
		Id uint `json:"id"`
	}{}
	if err := ctx.ShouldBind(&req); err != nil {
		res.SetRes(1, "参数解析错误", nil)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}

	userId := id.(uint)
	address := models.Address{}
	address.ID = req.Id
	fmt.Println(req.Id)
	address.UserId = userId
	err := address.Delete()

	if err != nil {
		res.SetRes(1, "删除记录失败", err)
		ctx.JSON(http.StatusBadRequest, res)
		return
	}
	res.SetRes(0, "success", "")
	ctx.JSON(http.StatusOK, res)

}
